<template>
  <div class="server-main">
    <el-form :inline="true" v-model="modelData" class="search-form">
      <el-form-item label="属性名" class="form-input">
        <el-input v-model.trim="modelData.name" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button id="btn" type="primary" size="small" @click="onSubmit(1)"
          >查询</el-button
        >
      </el-form-item>
    </el-form>

    <div class="server-table">
      <div class="table-title">
        <span class="table-title-text">边属性</span>
        <div>
          <el-button type="primary" size="small" @click="openCreateProperty"
            >新增边属性</el-button
          >
          <el-button type="primary" size="small" @click="goBack"
            >返回</el-button
          >
        </div>
      </div>
      <el-table
        :data="tableList"
        :cell-style="{ color: '#333333' }"
        :header-cell-style="{ background: '#F3F4F7', color: '#000000' }"
      >
        <el-table-column
          type="index"
          label="ID"
          width="50"
          align="center"
          fixed="left"
        ></el-table-column>
        <el-table-column
          prop="propertyName"
          label="属性名"
          align="center"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="propertyType"
          label="属性值类型"
          align="center"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <span>{{ getPropertyType[scope.row.propertyType] }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" align="center" width="200">
          <template slot-scope="scope">
            <el-link
              :underline="false"
              type="primary"
              class="ontology-edit"
              :disabled="scope.row.insertMethod === 1"
              @click="openEditOntology(scope.row)"
              >编辑</el-link
            >
            <el-link
              :underline="false"
              type="primary"
              class="ontology-edit"
              :disabled="scope.row.insertMethod === 1"
              @click="deleteProperty(scope.row.propertyId)"
              >删除</el-link
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        small
        layout="total, prev, pager, next, sizes, jumper"
        :page-sizes="[10, 20, 30]"
        :total="total"
        :hide-on-single-page="!total"
        :page-size.sync="modelData.pageSize"
        :pager-count="7"
        :current-page="modelData.pageNum"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      >
      </el-pagination>
    </div>
    <el-dialog
      :title="dialogConfig[dialogType].title"
      :visible.sync="dialogFormVisible"
      @close="afterDialogClose"
    >
      <el-form
        :model="modelParams"
        :rules="rules"
        ref="dialogForm"
        label-position="right"
        label-width="120px"
      >
        <el-form-item
          label="所属关系:"
          prop="relationName"
          class="dialog-inline"
        >
          <span>{{ modelParams.relationName }}</span>
        </el-form-item>
        <el-form-item
          label="属性名称:"
          prop="propertyName"
          class="dialog-inline"
        >
          <el-input
            maxlength="50"
            show-word-limit
            v-model.trim="modelParams.propertyName"
          >
          </el-input>
        </el-form-item>
        <el-form-item
          label="属性值类型:"
          prop="propertyType"
          class="dialog-inline"
        >
          <el-select
            v-model="modelParams.propertyType"
            @change="changePropertyType"
            style="width: 100%"
          >
            <el-option
              v-for="item in propertyTypeOptions"
              :key="item.key"
              :value="item.key"
              :label="item.label"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="
            modelParams.propertyType == 'int' ||
            modelParams.propertyType == 'float'
          "
          label="计量单位:"
          prop="measureUnit"
          class="dialog-inline"
        >
          <el-input
            style="width: 100%"
            type="input"
            v-model.trim="modelParams.measureUnit"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="约束类型:"
          prop="propertyBind"
          class="dialog-inline"
        >
          <el-select
            v-model="modelParams.propertyBind"
            :disabled="modelParams.propertyBindDisabled"
            style="width: 100%"
          >
            <el-option
              v-for="item in getBindOptions(bindOptions)"
              :key="item.key"
              :value="item.key"
              :label="item.label"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="约束配置:"
          class="dialog-inline"
          v-if="
            modelParams.propertyBind && modelParams.propertyBind != 'no_bind'
          "
        >
          <div v-if="modelParams.propertyBind == 'enum'">
            <el-form-item prop="enumNames">
              <span
                style="position: relative; margin-right: 10px"
                v-for="(item, index) in modelParams.enumNames"
                :key="item.key"
              >
                <el-input
                  v-if="
                    modelParams.propertyType != 'date' &&
                    modelParams.propertyType != 'datetime'
                  "
                  style="width: 154px; margin-bottom: 10px"
                  v-model="modelParams.enumNames[index]"
                ></el-input>
                <el-date-picker
                  style="width: 154px; margin-bottom: 10px"
                  v-if="modelParams.propertyType == 'date'"
                  v-model="modelParams.enumNames[index]"
                  align="right"
                  type="date"
                  placeholder="选择日期"
                  value-format="yyyy-MM-dd"
                  :clearable="false"
                >
                </el-date-picker>
                <el-date-picker
                  v-if="modelParams.propertyType == 'datetime'"
                  style="width: 154px; margin-bottom: 10px"
                  v-model="modelParams.enumNames[index]"
                  type="datetime"
                  placeholder="选择日期时间"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  :clearable="false"
                >
                </el-date-picker>
                <i
                  style="
                    position: absolute;
                    right: 2px;
                    top: 1px;
                    color: #1b85ff;
                    cursor: pointer;
                  "
                  class="el-icon-close"
                  @click="modelParams.enumNames.splice(index, 1)"
                ></i>
              </span>
              <span
                style="
                  border-radius: 3px;
                  padding: 5px;
                  color: #1b85ff;
                  border: 1px solid;
                  margin: 15px;
                  cursor: pointer;
                "
                @click="modelParams.enumNames.push('')"
                >新增</span
              >
            </el-form-item>
          </div>
          <div v-else>
            <el-row>
              <el-col :span="11">
                <el-form-item prop="startRange">
                  <el-input
                    v-if="
                      modelParams.propertyType != 'date' &&
                      modelParams.propertyType != 'datetime'
                    "
                    v-model="modelParams.startRange"
                    style="width: 133px"
                  ></el-input>
                  <el-date-picker
                    :picker-options="pickerOptionsStart(modelParams.endRange)"
                    style="width: 133px"
                    v-if="modelParams.propertyType == 'date'"
                    v-model="modelParams.startRange"
                    align="right"
                    type="date"
                    placeholder="选择日期"
                    value-format="yyyy-MM-dd"
                    :clearable="false"
                  >
                  </el-date-picker>
                  <el-date-picker
                    :picker-options="pickerOptionsStart(modelParams.endRange)"
                    v-if="modelParams.propertyType == 'datetime'"
                    style="width: 133px"
                    v-model="modelParams.startRange"
                    type="datetime"
                    placeholder="选择日期时间"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    :clearable="false"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="2" style="text-align: center">
                <span> ~ </span>
              </el-col>
              <el-col :span="11">
                <el-form-item prop="endRange">
                  <el-input
                    v-if="
                      modelParams.propertyType != 'date' &&
                      modelParams.propertyType != 'datetime'
                    "
                    v-model="modelParams.endRange"
                    style="width: 133px"
                  ></el-input>
                  <el-date-picker
                    style="width: 133px"
                    v-if="modelParams.propertyType == 'date'"
                    v-model="modelParams.endRange"
                    align="right"
                    type="date"
                    placeholder="选择日期"
                    value-format="yyyy-MM-dd"
                    :clearable="false"
                    :picker-options="pickerOptionsEnd(modelParams.startRange)"
                  >
                  </el-date-picker>
                  <el-date-picker
                    :picker-options="pickerOptionsEnd(modelParams.startRange)"
                    v-if="modelParams.propertyType == 'datetime'"
                    style="width: 133px"
                    v-model="modelParams.endRange"
                    type="datetime"
                    placeholder="选择日期时间"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    :clearable="false"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetDialogForm">取 消</el-button>
        <el-button type="primary" @click="submitDialogForm" :loading="loading"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { mapState, mapMutations } from "vuex";
export default {
  name: "OntologyManagement",
  components: {},
  data: () => {
    return {
      propertyTypeOptions: [
        { key: "text", label: "字符串" },
        { key: "int", label: "整数值" },
        { key: "float", label: "浮点值" },
        { key: "date", label: "日期" },
        { key: "datetime", label: "日期时间" },
        { key: "coordinate", label: "坐标" },
        { key: "array", label: "数组" },
        { key: "image", label: "图片" },
        { key: "file", label: "文件" },
      ],
      bindOptions: [
        { key: "no_bind", label: "无约束" },
        { key: "enum", label: "枚举值" },
        { key: "range", label: "范围值" },
      ],
      getPropertyType: {
        text: "字符串",
        int: "整数值",
        float: "浮点值",
        date: "日期",
        datetime: "日期时间",
        coordinate: "坐标",
        array: "数组",
        image: "图片",
        file: "文件",
      },
      ontologySpoId: "", // 节点 id
      propertyId: "", // 属性 id
      modelData: {
        name: "", // 本体类别名称
        propertyType: "",
        pageNum: 1, // 页码
        pageSize: 10, // 每页条数
      },
      tableList: [], // 本体类别列表
      property: [], // 本体类别(节点)的属性列表
      total: 0, // 数据总条数
      loading: false,
      dialogFormVisible: false,
      editOntologyId: null, // 编辑本体类别的id
      modelParams: {
        propertyName: null, // 属性名称名称
        relationName: "", // 所属关系
        propertyType: "", // 属性值类型

        enumNames: [],
        startRange: "",
        endRange: "",
        propertyBind: "",
        measureUnit: "",
      },
      dialogType: "ADD",
      dialogConfig: {
        ADD: {
          title: "新增边属性",
          funcName: "createProperty",
        },
        EDIT: {
          title: "编辑边属性",
          funcName: "editProperty",
        },
      },
      rules: {
        propertyName: [
          {
            required: true,
            message: "请输入属性名称",
            trigger: "blur",
          },
        ],
        propertyType: [
          {
            required: true,
            message: "请输入属性值类型",
            trigger: "blur",
          },
        ],
        propertyBind: [
          {
            required: true,
            message: "请选择约束类型",
            trigger: "blur",
          },
        ],
        measureUnit: [
          {
            required: true,
            message: "请输入计量单位",
            trigger: "blur",
          },
        ],
        startRange: [
          {
            required: true,
            message: "请输入开始范围",
            trigger: "blur",
          },
        ],
        endRange: [
          {
            required: true,
            message: "请输入结束范围",
            trigger: "blur",
          },
        ],
        enumNames: [
          {
            required: true,
            message: "请输入枚举值",
            trigger: "blur",
          },
        ],
      },
    };
  },
  computed: {
    ...mapState({
      containerDom: (state) => state.server.containerDom,
    }),
  },
  async created() {
    this.ontologySpoId = this.$route.params.id;
    this.modelParams.relationName = this.$route.params.relationName;
    this.searchRelationProperty();
  },
  methods: {
    pickerOptionsStart(endRange) {
      return {
        disabledDate: (time) => {
          if (endRange && endRange !== "") {
            return time.getTime() > new Date(endRange).getTime() - 86400000;
          }
        },
      };
    },
    pickerOptionsEnd(startRange) {
      return {
        disabledDate: (time) => {
          if (startRange && startRange !== "") {
            return time.getTime() < new Date(startRange).getTime();
          }
        },
      };
    },
    changePropertyType(val) {
      if (["coordinate", "array", "image", "file"].includes(val)) {
        this.modelParams.propertyBind = "no_bind";
        this.modelParams.propertyBindDisabled = true;
      } else {
        this.modelParams.propertyBindDisabled = false;
      }
      if (["date", "datetime", "int", "float"].includes(val)) {
        this.modelParams.startRange = "";
        this.modelParams.endRange = "";
      }
      // 切换为字符串类型时 如果已经选择了范围约束类型 则重置
      if (val === "text" && this.modelParams.propertyBind === "range") {
        this.modelParams.propertyBind = "no_bind";
      }
    },
    getBindOptions(val) {
      if (this.modelParams.propertyType == "text") {
        return [
          { key: "no_bind", label: "无约束" },
          { key: "enum", label: "枚举值" },
        ];
      } else {
        return [
          { key: "no_bind", label: "无约束" },
          { key: "enum", label: "枚举值" },
          { key: "range", label: "范围值" },
        ];
      }
    },
    // 获取本体模型属性列表
    async searchRelationProperty() {
      const {
        pageNum,
        pageSize,
        propertyType,
        name: propertyName,
      } = this.modelData;
      let params = {
        ontologySpoId: this.ontologySpoId,
        propertyName,
        propertyType,
        pageNum,
        pageSize,
      };
      let res = await this.$axios.get(
        this.$api.ontologyModel.xinbiaoObj.searchRelationProperty,
        {
          params,
        }
      );
      if (res.data.code !== 200) {
        this.$message.warning(res.data.message);
        return;
      }
      this.total = res.data.data.total;
      this.tableList = res.data.data.list;
    },
    // 查询
    onSubmit(pageNum) {
      this.modelData.pageNum = pageNum ? pageNum : this.modelData.pageNum;
      this.searchRelationProperty();
    },
    // 修改当前页码
    handleCurrentChange(page) {
      this.modelData.pageNum = page;
      this.searchRelationProperty();
    },

    // 修改每页条数
    handleSizeChange(e) {
      this.modelData.pageSize = e;
      this.searchRelationProperty();
    },

    // 删除当前属性
    deleteProperty(id) {
      let params = {
        propertyId: id,
      };
      this.$confirm("此操作将删除此数据，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let res = await this.$axios.get(
            this.$api.ontologyModel.xinbiaoObj.deleteRelationProperty,
            {
              params,
            }
          );
          if (res.data.code !== 200) {
            this.$message.warning(res.data.message);
            return;
          }
          this.$message.success("删除成功");
          this.searchRelationProperty();
        })
        .catch((err) => {
          this.$message.info("已取消删除");
        });
    },

    // 打开编辑本体框(获取节点信息)
    openEditOntology(row) {
      this.dialogType = "EDIT";
      this.modelParams = row;
      this.modelParams.relationName = this.$route.params.relationName;
      this.modelParams.propertyBindDisabled = [
        "coordinate",
        "array",
        "image",
        "file",
      ].includes(row.propertyType);
      this.propertyId = row.propertyId;
      this.dialogFormVisible = true;
    },

    // 模态框关闭后
    afterDialogClose() {
      this.resetFormInfo();
    },
    // 打开新增本体框
    openCreateProperty() {
      this.dialogType = "ADD";
      this.modelParams.relationName = this.$route.params.relationName;
      this.dialogFormVisible = true;
    },
    goBack() {
      this.$router.go(-1);
    },
    // 取消
    resetDialogForm() {
      this.dialogFormVisible = false;
    },
    // 确定
    submitDialogForm() {
      this.$refs.dialogForm.validate((valid) => {
        if (valid) {
          let func = this.dialogConfig[this.dialogType].funcName;
          this[func]();
          this.dialogFormVisible = false;
        } else {
          return false;
        }
      });
    },
    // 创建本体
    createProperty() {
      this.modelParams.ontologySpoId = this.ontologySpoId;
      this.loading = true;
      this.$axios
        .post(
          this.$api.ontologyModel.xinbiaoObj.addRelationProperty,
          this.modelParams
        )
        .then((res) => {
          let code = res.data.code;
          if (+code !== 200) {
            this.$message.warning(res.data.message);
            this.loading = false;
            return;
          }
          this.resetFormInfo();
          this.$message.success("新增成功");
          this.loading = false;
          this.dialogFormVisible = false;
          this.onSubmit();
        })
        .catch((error) => {
          this.loading = false;
        });
    },
    // 编辑本体类别
    editProperty() {
      this.loading = true;
      this.$axios
        .post(
          this.$api.ontologyModel.xinbiaoObj.editRelationProperty,
          this.modelParams
        )
        .then((res) => {
          let code = res.data.code;
          if (+code !== 200) {
            this.$message.warning(res.data.message);
            this.loading = false;
            return;
          }
          this.resetFormInfo();
          this.$message.success("编辑成功");
          this.loading = false;
          this.dialogFormVisible = false;
          this.onSubmit();
        })
        .catch((error) => {
          this.loading = false;
        });
    },
    // 重置表单信息为默认值
    resetFormInfo() {
      this.modelParams = {
        // 属性
        propertyName: null, // 属性值名
        // propertyType: null, // 属性值类型
        propertyType: "", // 属性值类型

        enumNames: [],
        startRange: "",
        endRange: "",
        propertyBind: "",
        measureUnit: "",
      };
    },
  },
};
</script>
<style lang="scss" scoped>
.server-main {
  position: relative;

  .search-form {
    padding: 16px 32px;
    border-radius: 4px;
    background: #ffffff;

    .el-form-item {
      margin-bottom: 0;
    }

    .form-input {
      margin-right: 32px;

      /deep/ .el-input__inner {
        width: 240px;
        height: 32px;
        background: #ffffff;
        border-radius: 2px;
        border: 1px solid #e0e0e0;
      }
    }
  }

  .server-table {
    margin-top: 16px;
    padding: 16px 32px 64px;
    border-radius: 4px;
    background: #ffffff;

    .table-title {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .table-title-text {
        border-left: 5px solid $--color-primary;
        padding-left: 10px;
        margin: 8px 0;
        font-size: 16px;
        line-height: 16px;
      }

      margin-bottom: 10px;
    }

    .page-wrapper {
      margin-top: 28px;
      display: flex;
      justify-content: flex-end;
      color: rgba(0, 0, 0, 0.65);

      .data-counter {
        font-weight: 400;
        line-height: 32px;
        margin-right: 24px;
      }

      /deep/ .btn-prev,
      /deep/ .btn-next {
        margin: 0 4px;
        min-width: 28px;
        border-radius: 2px;
        border: 1px solid rgba(0, 0, 0, 0.15);
        padding: 0;
      }

      /deep/ .el-pager .number {
        min-width: 28px;
        height: 28px;
        border-radius: 2px;
        border: 1px solid rgba(0, 0, 0, 0.15);
        margin: 0 4px;
        cursor: pointer;
      }
    }
  }

  .ontology-edit {
    padding: 0 10px;

    & + .ontology-edit {
      border-left: 1px solid #dddddd;
    }
  }

  /deep/ .el-table__append-wrapper {
    padding: 10px;
  }

  .el-pagination {
    float: right;
    margin-top: 20px;

    .form-input /deep/ .el-input {
      width: 200px;
    }

    /deep/ .el-input__inner {
      height: 22px;
    }
  }

  /deep/ .el-dialog {
    width: 500px;
    border-radius: 5px;
  }

  .dialog-inline {
    /deep/ .el-form-item__content {
      width: 300px;
    }

    button.el-button {
      background-color: $--color-primary !important;
      color: #fff !important;
      line-height: 1.2;
    }
  }
}
</style>
